//
//  SEGVisitorAccessNumberViewModel.m
//  SEGViewModel
//
//  Created by 乔杨 on 2020/6/4.
//

#import "SEGVisitorAccessNumberViewModel.h"
#import "SEGVisitorAccessManager.h"

@implementation SEGVisitorAccessNumberViewModel

- (instancetype)init {
    self = [super init];
    if (self) {
        [self seg_createCommand];
    }
    return self;
}
- (void)seg_createCommand {
    @weakify(self);
    self.command = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            // 请求访问次数
            [[SEGVisitorAccessManager shareManager] requestAccessNumber:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    self.accessNumberArray = [NSMutableArray array];
                    NSArray *resultArr = [[result valueForKey:@"data"] valueForKey:@"result"];
                    if (resultArr && [resultArr isKindOfClass:[NSArray class]]) {
                        if (resultArr.count > 0 && [resultArr[0] isKindOfClass:[NSDictionary class]]) {
                            [resultArr enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL * _Nonnull stop) {
                                NSString *value = [dic valueForKey:@"value"];
                                if (value && value.length > 0) {
                                    [self.accessNumberArray addObject:value];
                                }
                                if ([value isEqualToString:@"1"]) {
                                    self.selectedIndex = idx;// 默认选中一次
                                }
                            }];
                        }
                    }
                    [subscriber sendNext:self.accessNumberArray];
                    [subscriber sendCompleted];
                } else {
                    NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                    [subscriber sendError:error];
                }
            }];
            return nil;
        }];
    }];
}

@end
